package utils.others
{
	import flash.display.BitmapData;
	import flash.geom.ColorTransform;
	import flash.geom.Matrix;
	import flash.geom.Rectangle;
	import flash.text.TextField;
	import flash.text.TextFormat;
	import flash.utils.Dictionary;
	
	/**
	 * 字体工具
	 * 用于生成图片文字和处理HTML文字
	 * @author WLDragon 2013-11-08
	 */
	public class FontUtil
	{
		/**
		 * 获取像素文字(仅限于一行)
		 * 返回的图片文字高度为24像素，只有这个尺寸的
		 * @param	text  文字
		 * @param	color 颜色
		 * @param   isCache 是否缓存
		 * @return
		 */
		public function getPixelWord(text:String, color:uint = 0x000000, isCache:Boolean = true):BitmapData
		{
			if (wordCache[text] != undefined)
				return wordCache[text];
			
			var tf:TextFormat = new TextFormat("宋体", 12, color);
			var txt:TextField = new TextField;
			txt.defaultTextFormat = tf;
			txt.text = text;
			
			var w:int = 24 * txt.length;
			var b:BitmapData = new BitmapData(w, 24, true, 0x000000);
			b.draw(txt, new Matrix(1, 0, 0, 1, -2, -2));
			
			//因为draw的源是BitmapData,缩放才会产生锯齿,所以用bb再draw一次
			var bb:BitmapData = new BitmapData(b.width, b.height, true, 0x000000);
			bb.draw(b, new Matrix(2, 0, 0, 2));
			
			b.dispose();
			b = null;
			
			if(isCache)
				wordCache[text] = bb;
			
			return bb;
		}

		/**
		 * 
		 * @param	num     需要显示的数字序号
		 * @param	url     资源路径
		 * @param	color   转换的颜色
		 * @param	clipNum 切片数
		 * @return
		 */
		public function getNumberBitmapData(num:String, url:String, color:uint = 0x000000 ,clipNum:int = 10):BitmapData
		{
			if (numberCache[url+num+color] == null)
			{
				var source:BitmapData = App.asset.getBitmapData(url);
				var pw:int = source.width / clipNum;
				var ph:int = source.height;
				var len:int = num.length;
				var bmd:BitmapData = new BitmapData(pw * len, ph, true, 0x000000);
				
				var ct:ColorTransform = new ColorTransform();
				ct.color = color;
				var mt:Matrix = new Matrix();
				for (var i:int = 0; i < len; i++)
				{
					var n:int = int(num.charAt(i));
					//源图向左偏移
					mt.tx = -((n - i) * pw);
					//把指定范围内在源图的内容画到目标图的相同位置
					bmd.draw(source, mt, ct, null, new Rectangle(pw * i, 0, pw, ph));
				}
				numberCache[url+num+color] = bmd;
			}
			return numberCache[url+num+color];
		}
		
		/**文字缓存字典*/
		private var wordCache:Dictionary = new Dictionary;
		/**位图数字字缓存字典*/
		private var numberCache:Dictionary = new Dictionary;
	}

}